#include<func.h>

typedef struct 
{
    int tickets;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
}data_t;


void *pthread_sale1(void *p)//卖票窗口一
{
    data_t *d=p;
    while(1)
    {   
        pthread_mutex_lock(&d->mutex);
        if(d->tickets>0)
        {
            d->tickets--;
            printf("windows1 sale tickets=%d\n",d->tickets);
            if(0==d->tickets)
            {
                pthread_cond_signal(&d->cond);//余票为零时唤醒补票线程
            }
            pthread_mutex_unlock(&d->mutex);
        }
        else{
            pthread_mutex_unlock(&d->mutex);
            break;
        }
        sleep(1);
    }
    pthread_exit(NULL);

}

void *pthread_sale2(void *p)//卖票窗口一
{
    data_t *d=p;
    while(1)
    {   
        pthread_mutex_lock(&d->mutex);
        if(d->tickets>0)
        {
            d->tickets--;
            printf("windows2 sale tickets=%d\n",d->tickets);
            if(0==d->tickets)
            {
                pthread_cond_signal(&d->cond);
            }
            pthread_mutex_unlock(&d->mutex);
        }
        else{
            pthread_mutex_unlock(&d->mutex);
            break;
        }
        sleep(1);
    }
    pthread_exit(NULL);

}

void *pthread_tickets_add(void *p)//当票数等于0时，再补充十张票
{   
    data_t *d=p;
    pthread_mutex_lock(&d->mutex);
    if(d->tickets>0)
    {
    pthread_cond_wait(&d->cond,&d->mutex);//等待信号激活线程
    d->tickets=10;
    printf("tickets added\n");
    }
    pthread_mutex_unlock(&d->mutex);
    pthread_exit(NULL);
}

int main()
{
    pthread_t pthid[3];
    data_t d;
    d.tickets=20;
    pthread_mutex_init(&d.mutex,NULL);//初始化锁
    pthread_cond_init(&d.cond,NULL);//初始化环境变量
    int ret=pthread_create(&pthid[0],NULL,pthread_sale1,(void *)&d);//创建第一个卖票子线程
    THREAD_ERR_CHECK(ret,"pthread_create")
    ret=pthread_create(&pthid[1],NULL,pthread_sale2,(void *)&d);//创建第二个卖票子线程
    THREAD_ERR_CHECK(ret,"pthread_create")
    ret=pthread_create(&pthid[2],NULL,pthread_tickets_add,(void *)&d);//创建一个补票进程
    THREAD_ERR_CHECK(ret,"pthread_create")
    pthread_join(pthid[0],NULL);
    pthread_join(pthid[1],NULL);
    pthread_join(pthid[2],NULL);
    printf("i am main\n");
    return 0;
}